<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Cache;

class Category extends Model
{
    protected $fillable = ['parent_id', 'name', 'thumb', 'url', 'content', 'sort_order', 'is_show'];

    function children()
    {
        return $this->hasMany('App\Models\Category', 'parent_id', 'id');
    }

    public function products()
    {
        return $this->belongsToMany('App\Models\Product');
    }

    static function get_categories()
    {
//        if (!Cache::has('lxmall_categories')) {
//            $categories = self::with(['children' => function ($query) {
//                $query->orderBy('sort_order');
//            }])->where('parent_id', "0")->orderBy('sort_order')->get();
//
//            Cache::forever('lxmall_categories', $categories);
//        }
//        return Cache::get('lxmall_categories');
//

        $categories = Cache::rememberForever('lxmall_categories', function () {
            return self::with(['children' => function ($query) {
                $query->orderBy('sort_order');
            }])->where('parent_id', "0")->orderBy('sort_order')->get();
        });

        return $categories;
    }

    static function check_children($id)
    {
        $category = self::with('children')->find($id);
        if ($category->children->isEmpty()) {
            return true;
        }
        return false;
    }
}
